package club.gskj.gulimall.order.config;

import club.gskj.gulimall.order.vo.PayVo;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/***
 *  支付宝配置类模板
 *  配置用户私钥、公钥。同步请求地址、异步请求地址。
 */
@ConfigurationProperties(prefix = "alipay")
@Component
@Data
public class AlipayTemplate {

    //在支付宝创建的应用的id
    private String app_id = "2016102300744568";

    // 商户私钥，您的PKCS8格式RSA2私钥
    private String merchant_private_key = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCuumLewlmmf67Lc61J/ApRoQcSCv1xtpDbQ4SIa73bVyUOTEYZtFEDklhurtFq54ioiFNvCqLtBMzSTOneKr8/0T75iMxyEJl22RnwsD7+vHm9VnP2HcLCzUqnTi8v+xOY0X7Kdo7Qfu/Yu0wMg67ZyOQJxi33QUgQQvViJeiG1gBTqHsCtE6Ip/pj+oXjRl45uaZytl7CXw5WIaX8CmjlGFVxRiw2InNpdx9KVev8p+kThaGIwhXHzF0o7RMYVHWWnObuah+hIGGN9rVgowCp6jhvu412J2pFHfEg5jb5/BGCZPTTdh5UC87UxwYrsPCkpE6s3HTwFj3m6hZzHbG7AgMBAAECggEAQheyynxNmRN3NPI+vFugM5xrpkGN+POL+8SgX1IR8OQX2j6zzYlNk8JJvSRXhs6p/MYEeV5Wnr1QFMSPOkCFM0idP5qlawgoZLJeg5LHYWg9zIblOlWrlDA/auXCJ64bjZTBFyidgPRjGWJPs/QjsbGxwJi8TmjdL3mEhGm+eTHdxjg8t69SfsV0TEeb0W1jVHtEOdBYfgxJ+CHUCgNT2ONsa0v+T5OihZVmQRWgSB6kfBrOvMV53EZ6HXEDpRsmWUcZe2vjvgSwl7RHcWIWjeNmLIonw9EmnrKvx4W/hgwST++7vIISUy5Q1dSj/dhKRrdEkDd4UXZXZBT9aUNigQKBgQDYaTAkVOOw6m02Ba22mAvx40zOe94Adet6wFEDBBCf7k5HStASEe0OsKeTA0v0rb+Qe9qxGiKb98uBgS1cWSwFzWe8G9BaR7i3LJip8MrbEl1w8xBze/+DPHh4hnjm7rSJ5VhZaVZn9cI3Z/AIVQwiDP2HvYsEa2Dt78VmStrkmwKBgQDOsSLIO480SMleTTMtgR8R9ZMmBfUn+dRWgiz0t4CHooKKFZqUidhOoXkdYkg44rxZD0zQAq+EXne2/wTUcfe4gKMTyeQxrYBhp8QffrLzV6C62QG4FHV+PVHm8+HUL+xCHUlKWNwK/k3YkJNk/2PkTzlx6OUA0I/L/DhbABTpYQKBgQCnTUJ7g+j2d3Twg5lVBNyPJoLVSmtI/eCK6Cx44WaczVVUxiBvJ86VQbp669yHjt7+qtFZgvPokbuRJbVUpFdlMPOWOAZuFO5XJbHsBww8Kkl0rWQ1c1IIOfKEcqj7FuUZieUwUkALZLG9tauaNW2I0XQawUy8oOqxZ2C7APmSKwKBgQCIAvx2cur7ZuJL0dVZnlxJvyYDoWv/0GCwRJ08s/w6RPBN2YWNNWBH7e37Lg+Ej3+Nw4myX/IL0vZIT2xoOE7g9JVbkkE9h4SxvmpKp18uzn0QN3jwH1ZpqgRZTCdRL+/yWb8+01aJTWsAlbLIhV7AgHm2waDgdl4Jx4F2MImSQQKBgQDMxsUnLiT6kP8lad/aBUUHgZiXtNdI2/RtHaggMsvE0TtH3Imb8xYigW35xTGhwAIK65ccaQEzFcjoORw7ey1kTECcZp+7isAO+wkdboEg0ZpSTe/oGCYq9ZGI9kOambpUOs1ZHL3OegGbpUmvatBoPp3oCBF77gbLcbFS1Ml5SA==";

    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    private String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp88bsojz9UEgAmhNh29ozmWXXPnvpP5N/hFWXxnucJ4SZguG26gx8hBSaXJOpeAUEcPKeTUJFCkzrzbRuD2Qd9M9rJ73mAmI3s1U3lrg6HD31vZJhe3FOuIrPL86lcF3FEgjzPeeQheBIECnH98nGYnvsEYXruLU58bGJDwEwkUyjo8Wvb1uj75h5ZbpyoHnoPCIr8iu1Nh6CW7oWuvAvlgXcOSMFKYAXlrPLsd+RggDBggWXs9IPmoA5KtasK9hjc8S5v+R93qoKMiOD3NcszwNIjxSIqiIXHov+a6BdczmGph4JDwHReF9SdkqBTc7IE+mySjTLQ5Gczz4PSZ+rQIDAQAB";

    // 服务器[异步通知]页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    private String notify_url = "http://x83g9kzz.dongtaiyuming.net/payed/notify";

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    //同步通知，支付成功，一般跳转到成功页
    private String return_url = "http://member.gulimall.com/memberOrder.html";

    // 签名方式
    private String sign_type = "RSA2";

    // 字符编码格式
    private String charset = "utf-8";

    // 支付宝网关； https://openapi.alipaydev.com/gateway.do
    private String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    /**
     * 该笔订单允许的最晚付款时间，逾期将关闭交易。
     * 取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
     * 该参数数值不接受小数点， 如 1.5h，可转换为 90m
     */
    private String timeout;

    /**
     * 通过携带参数，调用支付宝支付接口。完成支付功能。
     *
     * @param vo 携带支付宝必须参数
     */
    public String pay(PayVo vo) throws AlipayApiException {

        //AlipayClient alipayClient = new DefaultAlipayClient(AlipayTemplate.gatewayUrl, AlipayTemplate.app_id, AlipayTemplate.merchant_private_key, "json", AlipayTemplate.charset, AlipayTemplate.alipay_public_key, AlipayTemplate.sign_type);
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金额，必填
        String total_amount = vo.getTotal_amount();
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应：" + result);
        return result;
    }

    /***
     *  支付宝关闭订单请求
     * @param vo
     * @return
     * @throws AlipayApiException
     */
    public String tradeClose(PayVo vo) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);

        //设置请求参数
        AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
        //商户订单号，商户网站订单系统中唯一订单号
//        String out_trade_no = new String(request.getParameter("WIDTCout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        String out_trade_no = vo.getOut_trade_no();

        //支付宝交易号
//        String trade_no = new String(request.getParameter("WIDTCtrade_no").getBytes("ISO-8859-1"), "UTF-8");
        String trade_no = "";

        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"trade_no\":\"" + trade_no + "\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        System.out.println("支付宝响应: " + result);
        //输出
        return result;
    }
}
